#!/usr/bin/env perl
use warnings;
use strict;

use CGI;
use Digest::SHA qw(sha1_hex);

# change /path/to/includes to match your setup
BEGIN { use constant INCLUDES => '/path/to/includes'; }
BEGIN { require(INCLUDES . '/functions.pl'); }
BEGIN { require(INCLUDES . '/images.pl'); }

# define functions for later use
sub do_delete($);
sub do_thumbnail($);
sub do_rename($$);

# fetch cgi parameters
my $cgi = CGI->new;

my ($action, $hash, $hash2);
$action = $cgi->param('action') if (defined($cgi->param('action')));
$hash = $cgi->param('hash') if (defined($cgi->param('hash')));
$hash2 = $cgi->param('hash2') if (defined($cgi->param('hash2')));

unless (defined($action) and defined($hash) and defined($hash2)) {
   error BAD_CGI;
}

# verify credentials
if (sha1_hex($hash . SEED) ne $hash2) {
   error ACCESS_DENIED;
}

# perform correct action
if ($action eq 'delete') {
   my $filename;
   $filename = $cgi->param('image') if (defined($cgi->param('image')));
   $filename = sanitize_filename($filename);

   error BAD_CGI unless (defined($filename));

   do_delete($filename);
} elsif ($action eq 'make_thumbnail') {
   my $filename;
   $filename = $cgi->param('image') if (defined($cgi->param('image')));
   $filename = sanitize_filename($filename);

   error BAD_CGI unless (defined($filename));

   do_thumbnail($filename);
} elsif ($action eq 'rename') {
   my ($filename, $new_filename);
   $filename = $cgi->param('image') if (defined($cgi->param('image')));
   $new_filename = $cgi->param('filename') if (defined($cgi->param('filename')));
   $filename = sanitize_filename($filename);
   $new_filename = sanitize_filename($new_filename);

   error BAD_CGI unless (defined($filename) and defined($new_filename));

   do_rename($filename, $new_filename);
} else {
   error BAD_CGI;
}

# print out success message
html_begin;
html_title "Success";
html_body;
print "      <h1>Success</h1>\n      </p>Success</p>\n";
html_end;
exit;


# delete a given file
sub do_delete($) {
   my ($filename) = @_;
   my $thumbnail = get_thumbname($filename);

   error BAD_CGI unless (-e $filename);

   unlink $filename;
   unlink $thumbnail if (-e $thumbnail);
}

# generate a thumbnail
sub do_thumbnail($) {
   my ($filename) = @_;

   error BAD_CGI unless (-e $filename);

   my ($type, $width, $height) = get_image_info($filename);
   if ($type ne 'GIF' and $type ne 'JPEG' and $type ne 'PNG') {
      error BAD_FILE;
   }

   my $thumbnail = make_thumbnail($filename, $type, $width, $height);
}

# rename a file
sub do_rename($$) {
   my ($filename, $new_filename) = @_;
   my $thumbnail = get_thumbname($filename);
   my $new_thumbnail = get_thumbname($new_filename);

   error BAD_CGI unless (-e $filename);
   error DUPE_NAME if (-e $new_filename);
   error DUPE_NAME if (-e $thumbnail and -e $new_thumbnail);

   `mv $filename $new_filename`;
   `mv $thumbnail $new_thumbnail` if (-e $thumbnail);
}
